#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
class Solution {
    int tmp[50200];
public:
    int reversePairs(vector<int>& record) {
        return mergesort(record, 0, record.size() - 1);
    }
    int mergesort(vector<int>& record, int left, int right)
    {
        int ret = 0;
        if (left >= right)
            return 0;
        int mid = (left + right) >> 1;
        ret += mergesort(record, left, mid);
        ret += mergesort(record, mid + 1, right);
        int cur1 = left;
        int cur2 = mid + 1;
        int i = 0;
        while (cur1 <= mid && cur2 <= right)
        {
            if (record[cur1] <= record[cur2])
            {
                tmp[i++] = record[cur2++];
            }
            else
            {
                ret += right - cur2 + 1;
                tmp[i++] = record[cur1++];
            }
        }
        while (cur1 <= mid)
        {
            tmp[i++] = record[cur1++];
        }
        while (cur2 <= right)
        {
            tmp[i++] = record[cur2++];
        }
        for (int j = left; j <= right; j++)
        {
            record[j] = tmp[j - left];
        }
        return ret;
    }
};